import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@SpringBootTest
//@RunWith(SpingRunner.class)
public class WordToWord {
    @Test
    public void test() throws IOException {
        String templatePath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\template.docx";
        String targetPath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\target.docx";
        String pdfPath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\targetPdf.pdf";
        String imgPath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\img.jpg";
        XWPFTemplate template = XWPFTemplate.compile(templatePath);
        Map map = new HashMap<>();
        RowRenderData row0 = Rows.of("姓名", "球队", "球衣号").center().create();
        RowRenderData row1 = Rows.of("乔丹", "公牛", "23").center().textColor("FF0000").create();
        RowRenderData row2 = Rows.of("科比", "湖人", "24").center().textColor("FF00FF").create();
        RowRenderData row3 = Rows.of("詹姆斯", "骑士", "6").center().textColor("FFFF00").create();

        TableRenderData tableRenderData = Tables.create(row0, row1, row2, row3);

        PictureRenderData pictureRenderData = Pictures.ofLocal(imgPath).size(600, 300).create();
        map.put("title", "美国职业篮球");
        map.put("content", "超级巨星");
        map.put("table", tableRenderData);
        map.put("img", pictureRenderData);
        template.render(map);
        template.writeAndClose(Files.newOutputStream(Paths.get(targetPath)));

    }

    @Test
    public void wordtopdf() {
//        String targetPath = "C:\\Users\\yangjin\\Desktop\\市图书馆-二升三暑假班作文.docx";
//        String pdfPath = "C:\\Users\\yangjin\\Desktop\\市图书馆-二升三暑假班作文.pdf";
        String targetPath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\target.docx";
        String pdfPath = "D:\\work\\project\\wordopdf-server\\src\\main\\resources\\target.pdf";

        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(new File(targetPath)));
            PdfOptions options = PdfOptions.create();
            PdfConverter.getInstance().convert(document, Files.newOutputStream(Paths.get(pdfPath)), options);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void searchAndReplace(String srcPath, String destPath, HashMap<String, Object> map) {
        try {
            // 替换的的关键字存放到Set集合中
            Set<String> set = map.keySet();
            // 读取模板文档
            XWPFDocument document = new XWPFDocument(new FileInputStream(srcPath));
            /**
             * 替换段落中的指定文字
             */
            // 读取文档中的段落，回车符为一个段落。
            // 同一个段落里面会被“:”等符号隔开为多个对象
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                // 获取文档中当前的段落文字信息
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                List<XWPFRun> run = paragraph.getRuns();
                // 遍历段落文字对象
                for (int i = 0; i < run.size(); i++) {
                    // 获取段落对象
                    if (run.get(i) == null) {    //段落为空跳过
                        continue;
                    }
                    String sectionItem = run.get(i).getText(run.get(i).getTextPosition());    //段落内容
                    // 遍历自定义表单关键字，替换Word文档中的内容
                    Iterator<String> iterator = set.iterator();
                    while (iterator.hasNext()) {
                        // 当前关键字
                        String key = iterator.next();
                        // 替换内容
                        sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                    }
                    run.get(i).setText(sectionItem, 0);
                }
            }

            /**
             * 替换表格中的指定文字
             */
            //获取文档中所有的表格，每个表格是一个元素
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();   //获取表格内容
                int count = table.getNumberOfRows();    //表格的行数
                //遍历表格行的对象
                for (int i = 0; i < count; i++) {
                    XWPFTableRow row = table.getRow(i);    //表格每行的内容
                    List<XWPFTableCell> cells = row.getTableCells();   //每个单元格的内容
                    //遍历表格的每行单元格对象
                    for (int j = 0; j < cells.size(); j++) {
                        XWPFTableCell cell = cells.get(j);    //获取每个单元格的内容
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();      //获取单元格里所有的段落
                        for (XWPFParagraph paragraph : paragraphs) {
                            //获取段落的内容
                            List<XWPFRun> run = paragraph.getRuns();
                            // 遍历段落文字对象
                            for (int o = 0; o < run.size(); o++) {
                                // 获取段落对象
                                if (run.get(o) == null || run.get(o).equals("")) {
                                    continue;
                                }
                                String sectionItem = run.get(o).getText(run.get(o).getTextPosition());    //获取段落内容
                                if (sectionItem == null || sectionItem.equals("")) {    //段落为空跳过
                                    continue;
                                }
                                //遍历自定义表单关键字，替换Word文档中表格单元格的内容
                                for (String key : map.keySet()) {
                                    // 替换内容
                                    sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                                    run.get(o).setText(sectionItem, 0);
                                }
                            }
                        }
                    }
                }
            }
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        //替换的内容，根据key为关键字指定替换成value的值
        HashMap<String, Object> map = new HashMap<>();
        map.put("${title}", "回复单");
        map.put("${name}", "xx建筑有限公司");
        map.put("${date}", "2021-12-30");
        map.put("${data}", "财务部");
        map.put("${mqdata}", "泉水项目部");
        map.put("${text}", "remark info");

        String srcPath = "D:\\text.docx";   //模板文件的地址
        String destPath = "D:\\test2.docx"; //替换后保存的地址
        searchAndReplace(srcPath, destPath, map);
    }
}
